<template>
    <view class="content">
        <van-nav-bar :title="navBarTitle" left-arrow @click-left="onClickLeft" class="navBar" :border="true">
        </van-nav-bar>

        <scroll-view class="scroll-content" scroll-y :lower-threshold="80" @scroll="scrollPage" show-scrollbar="false">

            <view class="tabTop">
                <!-- <view class="title"> {{navBarTitle}}</view> -->
                <form>
                    <view class="userInfoBox">
                        <view class="formItem">
                            <label>收货人</label>
                            <van-field class="uni-input" focus placeholder="请输入您的姓名" @change="changeName"
                                placeholder-style="" hold-keyboard="true" custom-style="color:#111111; font-size:14px;"
                                :value="userInfo.realName" :border="noBorder" />
                        </view>
                        <view class="formItem">
                            <label>手机号</label>
                            <van-field class="uni-input" focus placeholder="请输入您的手机号" @input="handlePhoneInput"
                                :value="userInfo.phone" :border="noBorder" type="number" hold-keyboard="true"
                                custom-style="color:#111111; font-size:14px;" />
                        </view>
                        <view class="formItem">
                            <label>所在地址</label>
                            <!-- <van-field class="uni-input" focus placeholder="所在地区" readonly clickable
                                @click.native="showSelector" :border="noBorder" hold-keyboard="true"
                                custom-style="color:#111111; font-size:14px;">
                                <template #input>
                                    <view class="address-display">
                                        <view class="main-address">{{ userInfo.detail  }}</view>
                                        <view class="detail-address">{{ userInfo.region  }}</view>
                                    </view>
                                </template>
                                <van-icon slot="right-icon" name="location" size="20" color="#FF6203"
                                    @tap.stop="toMap" />
                            </van-field> -->
                            <van-field class="uni-input" focus placeholder="选择收货地址" :value="userInfo.addressDetail"
                                readonly clickable @click.native="showSelector" :border="noBorder" hold-keyboard="true"
                                custom-style="color:#111111; font-size:14px;">
                                <van-icon slot="right-icon" name="location" size="20" color="#FF6203"
                                    @tap.stop="toMap" />
                            </van-field>
                            <selector-component :show="selectorVisible" key="3LMBZ-65DKB-MCBUG-NVM5T-4PSX5-PWBGL"
                                referer="citySelector" :hotCitys="hotCitys" @select="onSelectCity"></selector-component>
                        </view>
                        <view class="formItem">
                            <label>详细地址</label>
                            <van-field class="uni-input" focus placeholder="请输入您的小区名称 具体门牌号" @change="changeDoorNumber"
                                :value="userInfo.houseNumber" :border="noBorder" hold-keyboard="true"
                                custom-style="color:#111111; font-size:14px;" />
                        </view>

                        <view class="defaultBox">
                            <view class="setDefault">设置为默认地址</view>
                            <van-switch :checked="userInfo.isDefault" @change="onChangeDefault" active-color="#FF6203"
                                inactive-color="#e6e6e6" size="36rpx"></van-switch>
                        </view>
                    </view>
                    <view class="pasteAddress">
                        <view class="pasteTitle">智能识别</view>
                        <view class="pasteText">
                            <view style="min-height: 150rpx;">
                                <textarea placeholder="点击粘贴信息，可自动识别粘贴信息" @tap="openAddressInput" :value="clipboardData"
                                    placeholder-style="font-size: 12px;color: #888888;" :disable-default-padding="true"
                                    auto-focus="true" confirm-type="done" maxlength="200" autoHeight
                                    custom-style="font-size: 12px;line-height:2; color:#888888;">
                                </textarea>
                            </view>
                            <view class="pasteButton" @tap="getClipboardData">粘贴并识别地址</view>
                        </view>
                    </view>
                    <view class=" btn-area" style="padding-left:48rpx;padding-right: 48rpx;">
                        <!-- <button style="margin: 30px 0" type="waring" plain form-type="submit" class="button">保存并使用</button> -->
                        <van-button type="primary" @click="formSubmit">保存并使用</van-button>
                    </view>
                </form>
            </view>
        </scroll-view>
        <van-toast id="van-toast" />
        <van-popup position="bottom" :show="showAreaPicker">
            <van-area :area-list="areaList" @confirm="onAreaConfirm" @cancel="showAreaPicker = false" />
        </van-popup>

    </view>
</template>

<script>
import {areaList} from '@/utils/area.js'
import {addUserAddressApi } from '@/api/mine'
const chooseLocation = requirePlugin('chooseLocation');
export default {
    data() {
        return {
            navBarTitle: '新增地址',
            scrolling:false,
            // checked:false,
            userInfo:{
                region:'',
                realName:'',
                phone:'',
                address:'',
                provinceName:'',
                cityName:'',
                districtName:'',
                addressDetail:'', //所在区域address 地图选点返回的地址
                houseNumber:'', // 门牌号
                isDefault:false,
                latitude:'',
                longitude:'',
                postCode:undefined, // 邮政编码
                addressName:undefined, // 地址名称
            },
            noBorder:false,
            params:undefined, //接受从路由传过来的参数
            pageBiaoshi:'',
            clipboardData:undefined,
            showTip: true,
            showAreaPicker: false,
            areaList:require('@/utils/area.js'), // 需要准备地区数据文件
            selectorVisible: false,
            selectedProvince: null,
            selectedCity: null,
            hotCitys:'北京、上海、天津、重庆、广州、深圳、成都、杭州',

        }
    },
    onLoad(data) {
        if(data!==null){
            this.params=JSON.parse(decodeURIComponent(data.params))
            console.log(this.params)
        }
    },
    onShow(){
       
        // 地图选点插件选择完成后，会触发chooseLocation事件，我们可以在该事件中获取选择的位置信息
        const choosedLocation = chooseLocation.getLocation(); // 如果点击确认选点按钮，则返回选点结果对象，否则返回null
		console.log('选择的位置：', choosedLocation);
        if (choosedLocation) {
            this.userInfo.region = `${choosedLocation.province || ''} ${choosedLocation.city || ''} ${choosedLocation.district || ''}`.trim();
            this.userInfo.addressDetail = choosedLocation.address || choosedLocation.name || ''; //取返回的长地址
            this.userInfo.latitude = choosedLocation.latitude;
            this.userInfo.longitude = choosedLocation.longitude;
            this.userInfo.provinceName = choosedLocation.province || '';
            this.userInfo.cityName = choosedLocation.city || '';
            this.userInfo.districtName = choosedLocation.district || '';
            this.userInfo.address = chooseLocation.address || '';
            this.userInfo.addressName = choosedLocation.name || '';
        }

        // 城市选择插件
        // 从插件获取选择的城市信息
        const citySelector = requirePlugin('citySelector');
        const selectedCity = citySelector.getCity(); // 获取选中的城市
        console.log("selectedCity===", selectedCity);
        if (selectedCity) {
            console.log("selectedCity===", selectedCity);
        }
    },
    onReady() {
        // 页面加载完成后执行
        console.log('地区数据是否加载:', this.areaList);
    },
    onUnload() {
        // 页面卸载时清空插件数据，防止再次进入页面，getCity返回的是上次的结果
        const citySelector = requirePlugin('citySelector');
        citySelector.clearCity();
    },
    methods: {
        // 显示组件
        showSelector() {
            this.selectorVisible= true 
        },

        // 当用户选择了组件中的城市之后的回调函数
        onSelectCity(e) {
            const { province, city } = e.detail;
            this.selectedProvince = province
            this.selectedCity= city
        },
        // 打开地址输入框
        async openAddressPicker() { 

        },
        // 打开城市选择器
        goChooseCity() {
            const key = '3LMBZ-65DKB-MCBUG-NVM5T-4PSX5-PWBGL'; //使用在腾讯位置服务申请的key
            const referer = '17乐生活'; //调用插件的app的名称
            const hotCitys = '武汉,北京,上海,广州'; // 自定义热门城市列表，用,隔开，默认是北京,上海,广州,深圳,杭州,成都,南京,天津,重庆,西安,郑州,沈阳,青岛,济南,厦门,长沙
            const location = JSON.stringify({
                latitude: 39.89631551,
                longitude: 116.323459711,
            });
            uni.navigateTo({
                url: `plugin://citySelector/index?key=${key}&referer=${referer}&hotCitys=${hotCitys}`,
            });
        },
   
        // 滑动
        scrollPage(e) {
            console.log(e.detail.scrollTop, this.scrolling)
            if (e.detail.scrollTop > 25 && !this.scrolling) {
                this.scrolling = true
            } else if ((e.detail.scrollTop <= 25 && this.scrolling) || (e.detail.scrollTop <= 25 && !this.scrolling)) {
                this.scrolling = false
            }
        },
        // 返回键
        onClickLeft () {
            uni.navigateBack()
        },

        onAreaConfirm(event) {
            const { selectedOptions } = event.detail;
            const address = selectedOptions.map(item => item.name).join(' ');
            this.userInfo.address = address;
            this.showAreaPicker = false;
        },
        toMap() {
            const key = '3LMBZ-65DKB-MCBUG-NVM5T-4PSX5-PWBGL'; //使用在腾讯位置服务申请的key
            const referer = '17乐生活'; //调用插件的app的名称
            const location = JSON.stringify({
                latitude: 39.89631551,
                longitude: 116.323459711,
            });
            // const category = '生活服务,娱乐休闲';

            // 创建页面跳转事件通道
            const eventChannel = this.getOpenerEventChannel();
            console.log('location', 'zooooo')
            wx.navigateTo({
                url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}`,
                events: {
                    // 监听地图选点完成事件
                    chooseLocation: (res) => {
                        console.log('选择的位置信息:', res);
                        // 将选择的位置信息更新到表单
                        if (res) {
                            this.userInfo.address = `${res.province || ''} ${res.city || ''} ${res.district || ''}`.trim();
                            this.userInfo.detail = res.address || res.name || '';
                        }
                    }
                },
                success: (res) => {
                    console.log('地图插件打开成功');
                    // 设置30秒超时检测
                    setTimeout(() => {
                        if (!this.positionSelected) {
                            console.log('用户取消了位置选择');
                        }
                    }, 30000);
                },
                fail: (err) => {
                    console.error('打开地图失败:', err);
                    Toast.fail('无法打开地图');
                }
            });
            console.log('location', 'zoooowwwo')
        },
        // toMap(){
        //     uni.navigateTo({
        //         url: '/pages/other/mapSelect',
        //         events: {
        //             selectedLocation: (res) => {
        //                 console.log(res, 'resAddAddress')
        //                 this.userInfo.address = res.fullAddress; // 完整地址
        //                 this.userInfo.detail = res.detail.address; // 详细地址
        //                 // 如果需要保存经纬度
        //                 this.userInfo.latitude = res.detail.latitude;
        //                 this.userInfo.longitude = res.detail.longitude;
        //             }
        //         }
        //     })
        // },
    
        // 默认按钮  switch
        onChangeDefault(e){
            console.log(e,'e')
            this.userInfo.isDefault=e.detail
            console.log(this.userInfo.isDefault,'this.userInfo.isDefault')
        },
        // 修改名字
        changeName(e){
            console.log(e.detail,'e.detail   name')
            this.userInfo.realName=e.detail
        },
        // 修改电话
        handlePhoneInput(e){
            const inputValue = e.detail;
            const phoneRegex = /^1[3-9]\d{9}$/;
            // console.log(e,'输入手机号')
            if (!phoneRegex.test(inputValue)) {
                uni.showToast({
                    icon: 'none', // 不显示图标，最多显示2行
                    title: '手机号格式不正确',
                    // duration: 2000
                })
                console.log('请输入正确的手机号')
            } else {
                this.userInfo.phone = inputValue;
            }
            console.log(this.userInfo.phone,'this.userInfo.phone_number')
        },

        changeAddress(e){
            // this.us
        },
        
        // 门牌号
        changeDoorNumber(e){
            console.log(e.detail,'门牌号')
            this.userInfo.houseNumber=e.detail
        },
        handlePaste(event) {
            const pasteText = event.clipboardData.getData('text');
            // 这里可以添加地址识别的逻辑
            console.log('粘贴的内容:', pasteText);
        },
        showAreaPickerBox(){
            this.showAreaPicker = true
        },
        pasteAndRecognize() {
            // 模拟点击输入框触发粘贴事件
            const input = this.$refs.input;
            input.dispatchEvent(new Event('paste'));
        },
        // handlePaste() {
        //     // 简单的地址识别逻辑，可根据实际需求优化
        //     const text = this.pastedText;
        //     const provinceRegex = /^([\u4e00-\u9fa5]+(省|自治区|直辖市))/;
        //     const cityRegex = /([\u4e00-\u9fa5]+(市|自治州))/;
        //     const districtRegex = /([\u4e00-\u9fa5]+(区|县|县级市))/;

        //     const provinceMatch = text.match(provinceRegex);
        //     if (provinceMatch) {
        //         this.province = provinceMatch[1];
        //     }

        //     const cityMatch = text.match(cityRegex);
        //     if (cityMatch) {
        //         this.city = cityMatch[1];
        //     }

        //     const districtMatch = text.match(districtRegex);
        //     if (districtMatch) {
        //         this.district = districtMatch[1];
        //     }

        //     this.street = text.replace(provinceRegex, '').replace(cityRegex, '').replace(districtRegex, '').trim();
        // },



        // 修改粘贴地址识别方法
        async getClipboardData() {
            try {
                // 调用地址输入插件解析剪贴板内容
                const parsedAddress = await this.addressService.parseAddress({
                    rawText: this.clipboardData,
                    userId: getApp().globalData.userInfo.id
                });

                if (parsedAddress) {
                    this.userInfo.realName = parsedAddress.name || '';
                    this.userInfo.phone = parsedAddress.mobile || '';
                    this.userInfo.address = [
                        parsedAddress.province,
                        parsedAddress.city,
                        parsedAddress.district
                    ].join(' ');
                    this.userInfo.detail = parsedAddress.detail || '';

                    uni.showToast({ title: '地址识别成功', icon: 'success' });
                }
            } catch (error) {
                console.error('地址解析失败:', error);
                uni.showToast({
                    title: error.message || '地址解析失败',
                    icon: 'none',
                    duration: 3000
                });
            }
        },

        // 新增：调用地址输入插件弹窗
        async openAddressInput() {
            try {
                const result = await this.addressService.showInputDialog({
                    theme: '#FF6203',  // 使用配置中的主题色
                    autoGeocode: true
                });

                if (result) {
                    this.userInfo.address = result.formattedAddress;
                    this.userInfo.detail = result.street;
                    this.userInfo.latitude = result.location.lat;
                    this.userInfo.longitude = result.location.lng;
                }
            } catch (error) {
                uni.showToast({ title: '地址输入失败', icon: 'none' });
            }
        },

        // submit
        formSubmit() {
            // console.log('form发生了submit事件，携带数据为：', e.detail.value)
            console.log(this.userInfo,'this.userInfo','被点击了')
            const { realName, phone,addressDetail, isDefault } = this.userInfo;
            if (!realName || !phone || !addressDetail) {
                uni.showToast({
                    title: '请填写完整信息',
                    icon: 'none'
                });
                return;
            }
            const phoneRegex = /^1[3-9]\d{9}$/;
            if (!phoneRegex.test(phone)) {
                uni.showToast({
                    icon: 'none', // 不显示图标，最多显示2行
                    title: '请输入正确的手机号',
                    // duration: 2000
                })
            } else {
                addUserAddressApi({
                    realName: this.userInfo.realName,
                    phone: this.userInfo.phone,
                    provinceName: this.userInfo.provinceName,
                    cityName: this.userInfo.cityName,
                    districtName: this.userInfo.districtName,
                    detail:this.userInfo.addressDetail, //所在区域 地图返回的长的地址
                    houseNumber: this.userInfo.houseNumber, // 门牌号
                    isDefault: this.userInfo.isDefault,
                    latitude: this.userInfo.latitude,
                    longitude: this.userInfo.longitude,
                    postCode: this.userInfo.postCode || undefined,//邮编
                }).then(res => {
                    console.log(res,'res')
                    if (res.code === 200) {
                        uni.showToast({
                            icon: 'success', //最多显示7个汉字长度
                            // icon: 'none', // 不显示图标，最多显示2行
                            title: '编辑地址成功',
                            duration: 3000
                        })
                        setTimeout(() => {
                            // 3秒后执行页面跳转，这里假设跳转到名为 'otherPage' 的页面，需确保该页面已在小程序的页面配置中存在
                            uni.navigateBack()
                        }, 3000);
                    } else {
                        uni.showToast({ icon: 'none', title: res.msg || '提交失败' });
                    }
                }).finally(() => {
                    setTimeout(() => uni.navigateBack(), 3000);
                });

            }


        },
    }
}
</script>

<style scoped>
.content {
    background-color: #ffffff;
    display: flex;
    flex-direction:column;
    height:100vh;
    overflow:hidden;
    box-sizing: border-box;
}
.scroll-content {
    flex: 1;
    height: 1px;
}
.tabTop{
    padding:0px;
}
.title{
    font-size: 60rpx;
    line-height: 60rpx;
    text-align: left;
    color: #111111;
}
.userInfoBox{
    padding:0px 48rpx 40rpx 48rpx;
    border-bottom:4rpx solid #efefef;;
}
.formItem{
    margin-top: 40rpx;

}
.formItem label{
    font-size: 36rpx;
    text-align: left;
    color: #333;

}
.uni-input {
    /* background: #EEF7FE; */
    height: 53px;
    /* border-bottom: 1px solid #f9f9f9; */
}
.tips{
    font-size: 12px;
    text-align: left;
    color: #888888;
}
.defaultBox{
    margin-top: 40rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.setDefault{
    font-size: 24rpx;
    text-align: left;
    color: #888888;
}
.pasteAddress{
    margin-top: 52rpx;
    padding: 0 48rpx;
}
.pasteTitle{
    color: #111111;
    font-size: 28rpx;
    line-height: 28rpx;
}
/* 粘贴地址 */
.pasteText{
    margin-top: 28rpx;
    padding: 24rpx;
    background-color: rgba(247,247,247,1);
    /* width: 100%; */
    min-height: 264rpx;
}
/* 按钮 */
.pasteButton{
    float: right;
    color: rgba(255,98,3,1);
    font-size: 24rpx;
    line-height: 24rpx;
    height: 24rpx;
    cursor: pointer;
}

::v-deep .van-button--primary {
    width: 100%;
    height: 86rpx;
    border-radius: 38rpx;
    font-size: 28rpx;
    background: #FF6203 !important;
    border: 1px solid #ff6203 !important;
}

::v-deep .van-nav-bar__left {
    width: 56px;
    height: 44px;
}

::v-deep .navBar  .van-icon {
    color: #242629 !important;
}
::v-deep .van-cell{
    padding-left: 0px !important;
    border-bottom: 1px solid #f9f9f9;
}

</style>
